<template>
  <a-modal v-model:visible="config.visible" :title="config.title" :size="appStore.table.size" @cancel="handleCancel"
    @before-ok="handleBeforeOk">
    <a-form ref="formRef" :model="form" :rules="rules">
      <a-form-item label="名称" field="name">
        <a-input v-model="form.name" />
      </a-form-item>

      <a-form-item label="描述" field="description">
        <a-input v-model="form.description" />
      </a-form-item>

      <a-form-item label="排序" field="sort">
        <a-input v-model="form.sort" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
const emit = defineEmits(['ok']);

const appStore = useAppStore();
const formRef = ref();
const config = reactive({
  visible: false,
  isCreate: false,
  title: '',
});

const form = ref({
  id: undefined,
  name: undefined,
  description: undefined,
  sort: undefined,
});

const resetForm = () => {
  form.value = {
    id: undefined,
    name: undefined,
    description: undefined,
    sort: undefined,
  }
}


const rules = {
  name: [{ required: true, message: '请输入名称' }],
  sort: [{ required: true, message: '请输入排序' }],
};

const show = () => {
  formRef.value.resetFields();
  resetForm();
  config.isCreate = true;
  config.title = '新增';
  config.visible = true;
};

const showEdit = async (id: any) => {
  formRef.value.resetFields();
  resetForm();
  config.isCreate = false;
  config.title = '编辑';

  try {
    form.value = await axios.get(`/api/admin/resources-types/${id}`);
  } catch (e: any) {
    useHandleError(e);
  }

  config.visible = true;
};

const deleteAt = async (id: any) => {
  try {
    const data = { 'id': id, }
    await axios.postForm<any>(`/api/admin/resources-types/delete`, jsonToFormData(data));
    useNotificationSuccess('操作成功');
    emit('ok');
  } catch (e: any) {
    useHandleError(e);
  }
};


const handleCancel = () => {
  formRef.value.resetFields();
};
const handleBeforeOk = async (done: (closed: boolean) => void) => {
  const validateErr = await formRef.value.validate();
  if (validateErr) {
    done(false);
    return;
  }
  try {
    const url = config.isCreate
      ? '/api/admin/resources-types/create'
      : '/api/admin/resources-types/update';
    await axios.postForm<any>(url, jsonToFormData(form.value));
    useNotificationSuccess('操作成功');
    emit('ok');
    done(true);
  } catch (e: any) {
    useHandleError(e);
    done(false);
  }
};

defineExpose({
  show,
  showEdit,
  deleteAt,
});
</script>

<style lang="less" scoped></style>
